package com.liang.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.utils.PageUtils;
import com.liang.common.utils.Query;
import com.liang.common.utils.R;
import com.liang.gulimall.product.dao.ProductAttrValueDao;
import com.liang.gulimall.product.dao.SkuInfoDao;
import com.liang.gulimall.product.dao.SkuSaleAttrValueDao;
import com.liang.gulimall.product.dao.SpuInfoDescDao;
import com.liang.gulimall.product.entity.*;
import com.liang.gulimall.product.feign.SeckillFeignService;
import com.liang.gulimall.product.service.*;
import com.liang.gulimall.product.vo.SecKillSkuInfoVo;
import com.liang.gulimall.product.vo.SkuItemSaleAttrVo;
import com.liang.gulimall.product.vo.SkuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    SpuInfoDescDao spuInfoDescDao;
    @Autowired
    ProductAttrValueDao productAttrValueDao;
    @Autowired
    SpuInfoService  spuInfoService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    SeckillFeignService seckillFeignService;
    /**
     * 线程池
     */
    @Autowired
    ThreadPoolExecutor executor;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondiction(Map<String, Object> params) {
        /**
         * page: 1
         * limit: 10
         * key:
         * catelogId: 225
         * brandId: 1
         * min: 1
         * max: 3
         */
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(w->{
               w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)){
            try{
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le("price",max);
                }
            }catch (Exception e){

            }

        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> skuInfoEntities = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        return skuInfoEntities;
    }

    /**
     * 抽取封装商品详情Vo
     * 异步编排
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo=new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息pms_sku_info
            SkuInfoEntity skuInfoEntity = skuInfoDao.selectById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {//不需要1的结果
            //2、sku图片信息
            List<SkuImagesEntity> imagesEntityList = skuImagesService.list(new QueryWrapper<SkuImagesEntity>()
                    .eq("sku_id", skuId));
            skuItemVo.setImages(imagesEntityList);
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {//需要拿到1的结果才可执行
            //3、spu销售属性组合 一步查询
            List<SkuItemSaleAttrVo> skuItemSaleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(skuInfoEntity.getSpuId());
            skuItemVo.setSkuItemSaleAttrs(skuItemSaleAttrs);
        }, executor);
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {//需要拿到1的结果才可执行
            //4、spu介绍
            SpuInfoDescEntity descEntity = spuInfoDescDao.selectOne(new QueryWrapper<SpuInfoDescEntity>().eq("spu_id", skuInfoEntity.getSpuId()));
            skuItemVo.setDescribe(descEntity);
        }, executor);

        CompletableFuture<Void> baseFuture = infoFuture.thenAcceptAsync(skuInfoEntity -> {//需要拿到1的结果才可执行
            //5、spu规格参数  多步查询
            Long catalogId = skuInfoEntity.getCatalogId();
            List<AttrGroupEntity> attrGroupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catalogId));
            List<SkuItemVo.SpuItemBaseAttrVo> spuItemBaseAttrs = new ArrayList<>();
            for (AttrGroupEntity attrGroupEntity : attrGroupEntities) {
                if (attrGroupEntity != null) {
                    SkuItemVo.SpuItemBaseAttrVo spuItemBaseAttrVo = new SkuItemVo.SpuItemBaseAttrVo();
                    List<AttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupEntity.getAttrGroupId()));
                    List<SkuItemVo.BaseAttrVo> attrs = new ArrayList<>();

                    for (AttrAttrgroupRelationEntity attrgroupRelationEntity : attrgroupRelationEntities) {
                        ProductAttrValueEntity productAttrValueEntity = productAttrValueDao.selectOne(new QueryWrapper<ProductAttrValueEntity>().eq("attr_id", attrgroupRelationEntity.getAttrId()).eq("spu_id", skuInfoEntity.getSpuId()));
                        if (productAttrValueEntity!=null){
                            SkuItemVo.BaseAttrVo baseAttrVo = new SkuItemVo.BaseAttrVo();
                            baseAttrVo.setAttrValue(productAttrValueEntity.getAttrValue());
                            baseAttrVo.setAttrName(productAttrValueEntity.getAttrName());
                            attrs.add(baseAttrVo);
                        }
                    }
                    spuItemBaseAttrVo.setAttrGroupName(attrGroupEntity.getAttrGroupName());
                    spuItemBaseAttrVo.setAttrs(attrs);
                    spuItemBaseAttrs.add(spuItemBaseAttrVo);
                }
            }
            skuItemVo.setSpuItemBaseAttrs(spuItemBaseAttrs);
        }, executor);
        //6、是否参与秒杀
        CompletableFuture<Void> async = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSecKillInfo(skuId);
            if (r.getCode() == 0) {
                SecKillSkuInfoVo data = r.getData("data", new TypeReference<SecKillSkuInfoVo>() {
                });
                skuItemVo.setSeckillSkuVo(data);
            } else {
                log.error("远程调用失败");
            }
        }, executor);


        CompletableFuture.allOf(imageFuture,saleAttrFuture,descFuture,baseFuture,async).get();

        return skuItemVo;
    }


}